package com.xps.and.yuntong.Ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xps.and.yuntong.App;
import com.xps.and.yuntong.Data.bean1.LoginBean;
import com.xps.and.yuntong.Data.net.UserNetWorks;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.AppCommond;
import com.xps.and.yuntong.base.BaseActivity;
import com.jude.utils.JUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jpush.android.api.JPushInterface;
import rx.Subscriber;

/**
 * Created by administrator on 2017-12-09.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String PREFS_NAME = "YtUserInfo";

    private EditText etPhone, etPassword;
    private LinearLayout llLogin;
    private TextView tvFogretPassword, tvSiJiZhuCe, tv_logo;


    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void setData() {

    }

    @Override
    protected void init(Bundle inBundle) {
        initView();
        LoadUserDate();
        //需要的时候打开
//      trackApp = (App) getApplicationContext();

        Intent i = getIntent();
        if (i.getStringExtra("zhanghao") != null) {
            if (i.getStringExtra("zhanghao").equals("1")) {
                showCustomize();
            }
        }

//        boolean login = JUtils.getSharedPreference().getBoolean("User_Login", false);
//        if (login) {
//            startActivity(new Intent(LoginActivity.this, ShouYeActivity.class));
//            finish();
//        }

    }

    public void showCustomize() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(LoginActivity.this);
        final View dialogView = LayoutInflater.from(LoginActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText("您的账号在其他地方登录");
        customizeDialog.setTitle("温馨提示");
        customizeDialog.setView(dialogView);
        customizeDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        // CloseActivityClass.exitClient(LoginActivity.this);
                        dialog.dismiss();
                    }
                });
        customizeDialog.show();
    }

    private void initView() {
        etPhone = (EditText) findViewById(R.id.phone);
        etPassword = (EditText) findViewById(R.id.password);
        llLogin = (LinearLayout) findViewById(R.id.ll_login);
        tvFogretPassword = (TextView) findViewById(R.id.tv_forget_password);
        tvSiJiZhuCe = (TextView) findViewById(R.id.tv_siji_zhuce);
        tv_logo = (TextView) findViewById(R.id.tv_logo);

        llLogin.setOnClickListener(this);
        tvFogretPassword.setOnClickListener(this);
        tvSiJiZhuCe.setOnClickListener(this);
        tv_logo.setOnClickListener(this);
    }

    private void SaveUserDate() {
        // 载入配置文件
        SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
        // 写入配置文件
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("name", etPhone.getText().toString().trim());
        spEd.putString("userpassword", etPassword.getText().toString().trim());
        spEd.commit();
    }


    private void LoadUserDate() {
        SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
        String name = sp.getString("name", "");
        String userpassword = sp.getString("userpassword", "");
        if (!("".equals(name) && "".equals(userpassword))) {
            etPhone.setText(name);
            etPassword.setText(userpassword);
        }
    }


    @Override
    public void onClick(View v) {


        switch (v.getId()) {

            case R.id.tv_logo:
//              login();
                break;
            case R.id.ll_login:
                if (!ableGoNext()) return;
                showDialog();
                SaveUserDate();
//                Intent intent = new Intent(LoginActivity.this, DingdanKanActivity.class);
//                startActivity(intent);
                loginYt();
                break;

            case R.id.tv_forget_password:
                Intent intent2 = new Intent(LoginActivity.this, XiugaiPasswordTwoActivity.class);
                startActivity(intent2);
                break;
            case R.id.tv_siji_zhuce:
                Intent intent1 = new Intent(LoginActivity.this, RegistOneActivity.class);
                startActivity(intent1);
                break;

        }

    }

    //再按一次退出程序
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {

                finish();
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);
                //System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    void loginYt() {
        UserNetWorks.getLoginYt(etPhone.getText().toString().trim(), etPassword.getText().toString().trim(), "DRIVER", "", new Subscriber<LoginBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Log.e("111", "333");
//                Log.e("111", e.getMessage());
                JUtils.Toast("请检查网络1");
                dissmisDialog();
            }

            @Override
            public void onNext(LoginBean loginBean) {

                if (loginBean.getReturn_code().equals("SUCCESS")) {
                    Log.e("111", "2222");
//                    List<LoginBean.ReturnBodyBean> list = loginBean.getReturn_body();
                    LoginBean.ReturnBodyBean returnBodyBean = loginBean.getReturn_body();
                    Intent intent = new Intent(LoginActivity.this, ShouYeActivity.class);
                    SharedPreferences sp = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd = sp.edit();
                    spEd.putString("access_token", returnBodyBean.getAccess_token());
                    spEd.putInt("user_id", returnBodyBean.getUser_id());
                    spEd.putInt("sex", returnBodyBean.getSex());
                    spEd.putInt("avg_score", returnBodyBean.getAvg_score());
                    spEd.putInt("driver_id", returnBodyBean.getDriver_id());
                    spEd.putString("name", returnBodyBean.getName());
                    spEd.putString("mobile_phone", returnBodyBean.getMobile_phone());
                    spEd.putString("head_img", returnBodyBean.getHead_img());
                    spEd.putString("balance", returnBodyBean.getBalance());
                    spEd.putString("idcard_id", returnBodyBean.getIdcard_id());
                    spEd.putString("car_id", returnBodyBean.getCar_id());
                    spEd.putBoolean("User_Login", true);
                    spEd.putBoolean("User_Login1", false);
                    spEd.commit();

                    JPushInterface.setAliasAndTags(LoginActivity.this, returnBodyBean.getAccess_token().substring(0, 10), null, null);
                    startActivity(intent);
                    App.getInstance().prepareYingYan();
//                  trackApp.prepareYingYan();
                    dissmisDialog();
                    finish();
//                  JUtils.Toast(loginBean.getReturn_msg());
                } else if (loginBean.getReturn_code().equals("FAIL")) {
                    dissmisDialog();
                    JUtils.Toast(loginBean.getReturn_msg());
                }
            }
        });
    }

//    void login() {
//        UserNetWorks.getLogin(etPhone.getText().toString(), etPassword.getText().toString(), new Subscriber<UserBean>() {
//
//            @Override
//            public void onCompleted() {
//                dissmisDialog();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                e.printStackTrace();
//                JUtils.Toast("请检查网络");
//                dissmisDialog();
//            }
//
//            @Override
//            public void onNext(UserBean userBean) {
//                if (userBean.getReturn_code().equals("SUCCESS")) {
//                    if (true) {
//                        UserBean.ReturnBodyBean returnBodyBean = userBean.getReturn_body();
//                        SharedPreferences sp1 = JUtils.getSharedPreference();
//                        SharedPreferences.Editor spEd1 = sp1.edit();
//                        spEd1.putString("Access_token", returnBodyBean.getAccess_token());
//                        spEd1.putString("panduan", returnBodyBean.getDepositMoney() + "");
//                        spEd1.commit();
//                        if (returnBodyBean.getIsDeposit() == 0) {
//                            dissmisDialog();
//                            Intent intent = new Intent(LoginActivity.this, RegistFourActivity.class);
//                            intent.putExtra("DepositMoney", returnBodyBean.getDepositMoney() + "");
//                            startActivity(intent);
//                        } else if (returnBodyBean.getIsDeposit() == 1) {
//                            Intent intent = new Intent(LoginActivity.this, ShouYeActivity.class);
//                            intent.putExtra("userId", returnBodyBean.getUserId());
//                            intent.putExtra("Access_token", returnBodyBean.getAccess_token());
//
//                            SharedPreferences sp = JUtils.getSharedPreference();
//                            SharedPreferences.Editor spEd = sp.edit();
//
//                            spEd.putString("access_token", returnBodyBean.getAccess_token());
//                            spEd.putString("userId", returnBodyBean.getUserId() + "");
//                            spEd.putString("DriverId", returnBodyBean.getDriverId() + "");
//                            spEd.putString("headImg", returnBodyBean.getHeadImg() + "");
//                            spEd.putString("driverType", returnBodyBean.getDriverType() + "");
//                            spEd.putString("driverName", returnBodyBean.getName());
//                            spEd.putString("driverNickName", returnBodyBean.getNickName());
//                            spEd.putBoolean("User_Login", true);
//                            spEd.commit();
//
//                            JPushInterface.setAliasAndTags(LoginActivity.this, returnBodyBean.getAccess_token().substring(0, 10), null, null);
//                            startActivity(intent);
////                          trackApp.prepareYingYan();
//                            dissmisDialog();
//                            finish();
//                        }
//                    } else {
//                        Toast.makeText(getApplicationContext(), "请先阅读并同意《服务员合作协议》",
//                                Toast.LENGTH_SHORT).show();
//                    }
//                } else if (userBean.getReturn_code().equals("FAIL")) {
//                    Toast.makeText(getApplicationContext(), userBean.getReturn_msg(),
//                            Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
//    }

    boolean ableGoNext() {
        if (TextUtils.isEmpty(etPhone.getText().toString())) {
            JUtils.Toast("手机号不能为空");
            return false;
        } else if (TextUtils.isEmpty(etPassword.getText().toString())) {
            JUtils.Toast("密码不能为空");
            return false;
        }

        return true;
    }


}
